#!/bin/bash

# setup_simulator.sh
# Automatically finds or creates an iPhone 12 mini with iOS 16.4 for testing
# Caches the result to .stripe-ios-config for reuse

set -e

CONFIG_FILE=".stripe-ios-config"
DEVICE_TYPE="iPhone 12 mini"
IOS_VERSION="16.4"
SIMULATOR_NAME="iPhone 12 mini (Stripe)"

# Function to clear cache
clear_cache() {
    if [ -f "$CONFIG_FILE" ]; then
        rm "$CONFIG_FILE"
    fi
}

# Function to find existing simulator
find_existing_simulator() {
    # Extract UUID specifically (format: 8-4-4-4-12 hex digits)
    # This avoids extracting simulator names or states in parentheses
    xcrun simctl list devices available | grep "$DEVICE_TYPE.*$IOS_VERSION" | head -1 | sed -n 's/.*(\([A-F0-9]\{8\}-[A-F0-9]\{4\}-[A-F0-9]\{4\}-[A-F0-9]\{4\}-[A-F0-9]\{12\}\)).*/\1/p'
}

# Function to validate UUID format
validate_uuid() {
    local uuid="$1"
    [[ "$uuid" =~ ^[A-F0-9]{8}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{12}$ ]]
}

# Function to create new simulator
create_simulator() {
    xcrun simctl create "$SIMULATOR_NAME" "com.apple.CoreSimulator.SimDeviceType.iPhone-12-mini" "com.apple.CoreSimulator.SimRuntime.iOS-16-4"
}

# Function to validate simulator exists
validate_simulator() {
    local device_id="$1"
    xcrun simctl list devices | grep -q "$device_id"
}

# Main logic
main() {
    # Handle --clear-cache flag
    if [ "$1" = "--clear-cache" ]; then
        clear_cache
        return 0
    fi

    # Check if cached config exists and is valid
    if [ -f "$CONFIG_FILE" ]; then
        source "$CONFIG_FILE"

        # Validate cached ID has correct format and simulator still exists
        if [ -n "$DEVICE_ID_FROM_USER_SETTINGS" ] && validate_uuid "$DEVICE_ID_FROM_USER_SETTINGS" && validate_simulator "$DEVICE_ID_FROM_USER_SETTINGS"; then
            # Config is valid, export it
            export DEVICE_ID_FROM_USER_SETTINGS
            return 0
        else
            # Invalid or stale cache, clear it
            clear_cache
        fi
    fi

    # Look for existing simulator
    EXISTING_DEVICE=$(find_existing_simulator)

    if [ -n "$EXISTING_DEVICE" ]; then
        DEVICE_ID="$EXISTING_DEVICE"
    else
        DEVICE_ID=$(create_simulator)
        if [ -z "$DEVICE_ID" ]; then
            echo "Error: Failed to create simulator" >&2
            return 1
        fi
    fi

    # Validate the device ID before caching
    if ! validate_uuid "$DEVICE_ID"; then
        echo "Error: Extracted device ID '$DEVICE_ID' is not a valid UUID" >&2
        return 1
    fi

    # Save to config file as a proper shell script
    cat > "$CONFIG_FILE" << EOF
# Auto-generated by setup_simulator.sh
# This file is sourced to set up the simulator device ID
export DEVICE_ID_FROM_USER_SETTINGS="$DEVICE_ID"
EOF

    # Export for current session
    export DEVICE_ID_FROM_USER_SETTINGS="$DEVICE_ID"
}

# Show usage if requested
if [ "$1" = "--help" ] || [ "$1" = "-h" ]; then
    echo "Usage: source $0 [--clear-cache] [--help]"
    echo ""
    echo "Automatically finds or creates an iPhone 12 mini with iOS 16.4 for testing."
    echo "Caches the result to .stripe-ios-config for reuse."
    echo ""
    echo "Options:"
    echo "  --clear-cache    Clear the cached simulator ID"
    echo "  --help, -h       Show this help message"
    echo ""
    echo "Usage:"
    echo "  source ci_scripts/setup_simulator.sh"
    echo "  xcodebuild [...] -destination \"id=\$DEVICE_ID_FROM_USER_SETTINGS,arch=arm64\" [...]"
    echo ""
    echo "The script exports DEVICE_ID_FROM_USER_SETTINGS to your environment."
    return 0
fi

main "$@"